import { Form } from 'antd';
import { axconst } from '@/shared/axconst';
import { AxValidator } from '../AxValidator';
import React from 'react';
import './style.css';
import { AxFormItemBaseProps } from './AxFormItemBaseProps';

const FormItem = Form.Item;
const {
  inlineFormItemLayout,
  inlineFormItemLayoutNoLabel,
  inlineFormItemLayoutAllRowTwo,
  inlineFormItemLayoutAllRowThree,
} = axconst;

/** 表单控件的基类 */
export const AxFormItemBase: React.FC<AxFormItemBaseProps> = props => {
  const {
    wholerow,
    formItemLayoutFromProps,
    formItemClassName,
    label,
    required,
    message,
    len,
    min,
    max,
    minLength,
    maxLength,
    pattern,
    validator = AxValidator,
    form,
    field,
    value,
    hidden,
    fiExtra,
    children,
    WrappedComponent, //被包裹的组件
    showLabel = true,
    htmlHidden = false,
    valuePropName = {}, //Swhith组件用的
    fieldDecoratorOptions = {},
    placeholder = `请输入${label}`,
    fiValidateStatus,
    fiHelp,
    ...rest
  } = props;

  /** FormItem布局 */
  let formItemLayout = {};
  switch (wholerow) {
    case 'two':
      formItemLayout = { ...inlineFormItemLayoutAllRowTwo };
      break;
    case 'three':
      formItemLayout = { ...inlineFormItemLayoutAllRowThree };
      break;
    case 'none':
      formItemLayout = {};
      break;
    default:
      formItemLayout = formItemLayoutFromProps
        ? formItemLayoutFromProps
        : { ...inlineFormItemLayout };
      break;
  }
  /** 不展示label的布局 */
  if (!showLabel) {
    formItemLayout = inlineFormItemLayoutNoLabel
  }

  /** 校验规则 */
  const rule = {
    label,
    required,
    message,
    len,
    min,
    max,
    minLength,
    maxLength,
    pattern,
    validator,
  };

  return hidden ? null : (
    <FormItem
      {...formItemLayout}
      label={showLabel === true ? label : ''}
      // extra={fiExtra}
      className={formItemClassName}
      validateStatus={fiValidateStatus}
      help={fiHelp}
    >
      {/* AxLabel只用于展示，不必提交数据 */}
      {form && WrappedComponent.name !== 'AxLabel' ? form.getFieldDecorator(field, {
        ...valuePropName,
        initialValue: value,
        rules: [rule],
        ...fieldDecoratorOptions,
      })(
        <WrappedComponent hidden={htmlHidden} placeholder={placeholder} {...rest}>
          {children}
        </WrappedComponent>
      ) : (
          <WrappedComponent hidden={htmlHidden} placeholder={placeholder} value={value} {...rest}>
            {children}
          </WrappedComponent>
        )
      }
    </FormItem>
  );
};
